import * as express from "express";
import { debug } from "../utils/log";
import { Message } from "../utils/message";
import { normalizeQuery } from "../media/query";
import { getMP3, updateMP3 } from "../db/media";
import { routerDeleteByKey } from "../media/delete";
import {
	routerAudioUpload,
	routerMergeChunks,
	routerUploadChunks,
} from "../media/upload";
import { routerAudioDecode } from "../media/decode";
import { routerEditTags, routerEditTitle } from "../media/edit";

const router = express.Router();

router.get("/", async (req, res) => {
	const normalQuery = normalizeQuery(req.query);

	debug({
		url: "/",
		query: normalQuery,
	});

	const data = await getMP3(normalQuery);

	const msg = Message.success(data);
	res.send(msg);
});

router.get("/update", async (_req, res) => {
	debug({
		url: "/update",
	});
	await updateMP3();
	const data = {
		info: "UPDATE_DONE",
	};
	const msg = Message.success(data);
	res.send(msg);
});

/**
 * 重置数据库
 */
router.get("/reset", async (_req, res) => {
	await updateMP3();

	debug({
		url: "/reset",
	});

	res.send(
		Message.success({
			info: "RESET_DONE",
		})
	);
});

router.post("/upload", (req, res) => {
	routerAudioUpload(req, res);
});

router.get("/decode", async (req, res) => {
	await routerAudioDecode(req, res);
});

router.get("/edit", async (req, res) => {
	const { key, title, tags } = req.query;
	if (key && title) {
		await routerEditTitle(res, String(key), String(title));
	} else if (key && tags) {
		await routerEditTags(res, String(key), String(tags));
	} else {
		debug({ url: "/edit", key: String(key), error: "MISSING_PARAMS" });

		res.send(
			Message.success({
				info: "MISSING_PARAMS",
			})
		);
	}
});

router.delete("/", async (req, res) => {
	const { key } = req.query;
	if (key) {
		await routerDeleteByKey(res, String(key));
	} else {
		debug({
			key,
			url: "/",
			type: "delete",
			error: "MISSING_PARAMS",
		});

		res.send(
			Message.success({
				info: "MISSING_PARAMS",
			})
		);
	}
});

router.post("/upload-chunks", (req, res) => {
	routerUploadChunks(req, res);
});

router.post("/merge-chunks", (req, res) => {
	routerMergeChunks(req, res);
});

export default router;
